package com.chx.rpc04;

import com.chx.dto.User;
import com.chx.rpc01.UserServiceImpl;

import java.io.*;
import java.lang.reflect.Method;
import java.net.ServerSocket;
import java.net.Socket;

public class Server {

    private static boolean running=true;

    public static void main(String[] args) throws Exception {
        ServerSocket s = new ServerSocket(8080);
        while(running){
            Socket socket = s.accept();
            process(socket);
            socket.close();
        }
        s.close();
    }

    private static void process(Socket socket) throws Exception{
        InputStream is = socket.getInputStream();
        ObjectInputStream ois= new ObjectInputStream(is);
        String methodName = ois.readUTF();
        Class[] classes = (Class[]) ois.readObject();
        Object[] objects = (Object[]) ois.readObject();

        Method method = UserServiceImpl.class.getMethod(methodName, classes);
        User invoke = (User)method.invoke(UserServiceImpl.class.newInstance(),objects);

        OutputStream os = socket.getOutputStream();
        ObjectOutputStream oos = new ObjectOutputStream(os);
        oos.writeObject(invoke);
        oos.flush();

        ois.close();
        oos.close();
    }
}

